package com.tungse.juc.threadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Function;

/**
 * @Description:
 * @Author: Tungse
 *
 * 线程池的创建
 */
public class Executors_Demo {
    public static void main(String[] args) {
        // 创建一个单线程的线程池
//        ExecutorService executorService = Executors.newSingleThreadExecutor();
//        public static ExecutorService newSingleThreadExecutor() {
//            return new Executors.FinalizableDelegatedExecutorService
//                    (new ThreadPoolExecutor(1, 1,
//                            0L, TimeUnit.MILLISECONDS,
//                            new LinkedBlockingQueue<Runnable>()));
//        }

        // 创建一个固定大小的线程池
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);
//        public static ExecutorService newFixedThreadPool(int nThreads) {
//            return new ThreadPoolExecutor(nThreads, nThreads,
//                    0L, TimeUnit.MILLISECONDS,
//                    new LinkedBlockingQueue<Runnable>());
//        }

        // 创建一个可缓存的线程池
//        ExecutorService threadPool = Executors.newCachedThreadPool();
//        public static ExecutorService newCachedThreadPool() {
//            return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
//                    60L, TimeUnit.SECONDS,
//                    new SynchronousQueue<Runnable>());
//        }

        ExecutorService threadPool = new ThreadPoolExecutor(2, 5,
                10l, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());
        try {
            for (int i = 1; i <= 9; i++) {
                final int temp = i;
                threadPool.execute(() -> {

                    System.out.println(Thread.currentThread().getName() + "=== OK ==" + temp);
                });
            }
        } finally {
            threadPool.shutdown();
        }

        List<String> list = new ArrayList<>();
        list.forEach(System.out::println);
    }
}
